/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
// class Solution {
// public:
//     ListNode* detectCycle(ListNode* head) {
//         set<ListNode*> st;
//         ListNode* cur = head;
//         while (cur) {
//             if (st.count(cur))
//                 return cur;
//             st.insert(cur);
//             cur = cur->next;
//         }
//         return nullptr;
//     }
// };

class Solution {
public:
    ListNode* detectCycle(ListNode* head) {
        if (head == nullptr)
            return nullptr;
        ListNode *fast = head, *slow = head;
        bool vis = false;
        while (fast && fast->next) {
            fast = fast->next->next;
            slow = slow->next;
            if (fast == slow) {
                vis = true;
                break;
            }
        }
        if (!vis)
            return nullptr;
        ListNode* ps = head;
        while (ps != slow) {
            ps = ps->next;
            slow = slow->next;
        }
        return ps;
    }
};